#include "Mutex.hpp"
#include <string>
#include <unistd.h>
#include <functional>
#include <string.h>
#include <stdlib.h>
using namespace ve;
int tickets = 200; // 共享资源,临界资源

class thread_data
{
public:
    string _name;
    Mutex *_plock;
    thread_data(const string &name, Mutex *plock) : _name(name),
                                                    _plock(plock)
    {
    }
    ~thread_data() {}
};
void *routine(void *args)
{
    thread_data *id = static_cast<thread_data *>(args);
    while (1)
    {
        //id->_plock->lock();
        lockguard guard(*(id->_plock));
        if (tickets > 0)
        {
            usleep(10000);
            printf("%s sells ticket:%d\n", id->_name.c_str(), tickets);
            tickets--;
            //id->_plock->unlock();
        }
        else
        {
            //id->_plock->unlock();
            break;
        }
    }
    return nullptr;
}
int main()
{
    pthread_t t1, t2, t3, t4;
    Mutex lock;

    thread_data *p1 = new thread_data("thread 1", &lock);
    thread_data *p2 = new thread_data("thread 2", &lock);
    thread_data *p3 = new thread_data("thread 3", &lock);
    thread_data *p4 = new thread_data("thread 4", &lock);
    pthread_create(&t1, nullptr, routine, (void *)p1);
    pthread_create(&t2, nullptr, routine, (void *)p2);
    pthread_create(&t3, nullptr, routine, (void *)p3);
    pthread_create(&t4, nullptr, routine, (void *)p4);

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);

    // lock.~Mutex();//自动调用析构函数
    return 0;
}